package com.rzx.mybackend.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * DynamicTaskUtil
 *
 * @author renzhexian
 * @date 2025/10/13
 */

@Component
@RequiredArgsConstructor
public class DynamicTaskUtil {

    private final TaskScheduler taskScheduler;
    private final Map<String, ScheduledFuture<?>> taskRegistry = new ConcurrentHashMap<>();

    /**
     * 注册定时任务
     */
    public void scheduleTask(String taskId, Runnable task, String cronExpression) {
        // 如果任务已存在，先取消
        cancelTask(taskId);

        // 调度新任务
        ScheduledFuture<?> future = taskScheduler.schedule(task, new CronTrigger(cronExpression));
        taskRegistry.put(taskId, future);
    }

    /**
     * 取消指定任务
     */
    public boolean cancelTask(String taskId) {
        ScheduledFuture<?> future = taskRegistry.remove(taskId);
        if (future != null) {
            return future.cancel(false);
        }
        return false;
    }

    /**
     * 检查任务是否存在且未被取消
     */
    public boolean hasTask(String taskId) {
        ScheduledFuture<?> future = taskRegistry.get(taskId);
        return future != null && !future.isCancelled();
    }

    /**
     * 获取所有任务ID
     */
    public Set<String> getAllTaskIds() {
        return new HashSet<>(taskRegistry.keySet());
    }

    /**
     * 取消所有任务
     */
    public void cancelAllTasks() {
        taskRegistry.values().forEach(future -> future.cancel(false));
        taskRegistry.clear();
    }
}